package com.mzy.xmyx.acl.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mzy.xmyx.common.result.Result;
import com.mzy.xmyx.acl.service.AdminService;
import com.mzy.xmyx.acl.service.RoleService;
import com.mzy.xmyx.model.acl.Admin;
import com.mzy.xmyx.vo.acl.AdminQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/admin/acl/user")
@CrossOrigin
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @ApiOperation("获取后台用户分页列表(带搜索)")
    @GetMapping("/{current}/{limit}")
    public Result pageList(@PathVariable Integer current,
                           @PathVariable Integer limit,
                           AdminQueryVo adminQueryVo) {
        IPage<Admin> pageModel = adminService.selectPage(current, limit, adminQueryVo);
        return Result.ok(pageModel);
    }

    @ApiOperation("通过id查询用户")
    @GetMapping("/get/{id}")
    public Result getById(@PathVariable Long id) {
        Admin admin = adminService.getById(id);
        return Result.ok(admin);
    }

    @ApiOperation("添加用户")
    @PostMapping("/save")
    public Result save(@RequestBody Admin admin) {
        Boolean isSuccess = adminService.save(admin);
        return Result.ok(isSuccess);
    }

    @ApiOperation("通过id更新用户")
    @PutMapping("/update")
    public Result update(@RequestBody Admin admin) {
        boolean isSuccess = adminService.updateById(admin);
        return Result.ok(isSuccess);
    }

    @ApiOperation("通过id删除用户")
    @DeleteMapping("/remove/{id}")
    public Result removeById(@PathVariable Long id) {
        boolean isSuccess = adminService.removeById(id);
        return Result.ok(isSuccess);
    }

    @ApiOperation("批量删除用户通过ids")
    @DeleteMapping("/batchRemove")
    public Result batchRemove(@RequestBody List<Long> ids) {
        boolean isSuccess = adminService.removeByIds(ids);
        return Result.ok(isSuccess);
    }

    @ApiOperation("根据当前用户id获取所有角色和已分配的角色")
    @GetMapping("/toAssign/{adminId}")
    public Result toAssignByAdminId(@PathVariable Long adminId) {
        // map中分别存放：所有角色信息，当前用户已分配角色信息
        Map<String, Object> map = roleService.getRoleByAdminId(adminId);
        return Result.ok(map);
    }


    @ApiOperation("根据用户id分配角色")
    @PostMapping("/doAssign")
    public Result doAssignByAdminId(@RequestParam("adminId") Long adminId,
                                    @RequestParam("roleId") List<Long> roleIdList) {
        Boolean isSuccess = roleService.saveAdminRoleRelationship(adminId, roleIdList);
        return Result.ok(isSuccess);
    }


}
